package com.example.webshiro.base.dao;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

/**
 * <p>基础查询Service</p>
 * @author LuoYu
 * date 2021/2/4
 **/
public interface BaseService<E extends BaseEntity,ID extends Serializable>  {


    BaseDao<E,ID> getDao();

    default E save(E e){
        beforeSave(e);
       return getDao().save(e);
    }

    default Collection<E> saveEntities(Collection<E> entities){
        LocalDateTime now = LocalDateTime.now();
        entities.forEach(this::beforeSave);

        return getDao().saveAll(entities);
    }

    default void beforeSave(E e){
        if(e.getCreateTime() == null){
            e.setCreateTime(LocalDateTime.now());
        }
    }

    default List<E> findAll(){
        return getDao().findAll();
    }

    default List<E> findAll(Iterable<ID> ids){
        return getDao().findAllById(ids);
    }

    default  E getById(ID id){
        return getDao().getOne(id);
    }

    default E getByCondition(Specification<E> specification){
        return getDao().findOne(specification).orElse(null);
    }

    default List<E> getAllByCondition(Specification<E> specification){
        return getDao().findAll(specification);
    }


    default void deleteById(ID id){
        getDao().deleteById(id);
    }

    default boolean hasExists(ID id){
        return getDao().existsById(id);
    }

    default E saveAndFlash(E e){
        return getDao().saveAndFlush(e);
    }

    default Page<E> findAll(Pageable pageable){
        return getDao().findAll(pageable);
    }

    default Page<E> findAllByCondition(Specification<E> specification, Pageable pageable){
        return getDao().findAll(specification,pageable);
    }


































}
